<template>
  <view class="home-container">
    <!-- 营养知识轮播 -->
    <view class="banner-section">
      <swiper class="banner-swiper" indicator-dots circular autoplay>
        <swiper-item v-for="banner in bannerList" :key="banner.id" @click="viewBanner(banner)">
          <image :src="banner.image" class="banner-image" mode="aspectFill" />
          <view class="banner-overlay">
            <text class="banner-title">{{ banner.title }}</text>
          </view>
        </swiper-item>
      </swiper>
    </view>
  

    <!-- 快捷入口 -->
    <view class="quick-actions">
      <view class="action-item" @click="gotoRecommend">
        <uni-icons type="heart-filled" size="30" color="#ff4d4f" />
        <text class="action-text">菜品推荐</text>
      </view>
      <view class="action-item" @click="gotoNutrition">
        <uni-icons type="gear-filled" size="30" color="#52c41a" />
        <text class="action-text">营养优化</text>
      </view>
      <view class="action-item" @click="gotoSearch">
        <uni-icons type="search" size="30" color="#1890ff" />
        <text class="action-text">菜品搜索</text>
      </view>
      <view class="action-item" @click="gotoFavorites">
        <uni-icons type="star-filled" size="30" color="#faad14" />
        <text class="action-text">我的收藏</text>
      </view>
    </view>

    <!-- 热门菜品 -->
    <view class="hot-dishes">
      <view class="section-header">
        <text class="section-title">热门菜品</text>
        <view class="sort-options">
          <text 
            class="sort-item" 
            :class="{ active: sortType === 'rating' }"
            @click="changeSortType('rating')"
          >
            评分
          </text>
          <text 
            class="sort-item" 
            :class="{ active: sortType === 'favorite' }"
            @click="changeSortType('favorite')"
          >
            收藏
          </text>
        </view>
      </view>
      
      <view class="dish-list">
        <view 
          class="dish-item" 
          v-for="dish in hotDishes" 
          :key="dish.id"
          @click="viewDishDetail(dish.id)"
        >
          <image :src="dish.image" class="dish-image" mode="aspectFill" @error="onImageError" />
          <view class="dish-info">
            <text class="dish-name">{{ dish.name }}</text>
            <view class="dish-tags">
              <text class="tag cuisine">{{ dish.cuisine }}</text>
              <text class="tag taste">{{ dish.taste }}</text>
            </view>
            <view class="dish-meta">
              <uni-rate :value="dish.rating" :readonly="true" :size="12" />
              <text class="rating-text">{{ dish.rating ? dish.rating.toFixed(1) : '0.0' }}</text>
              <text class="favorite-count">{{ dish.favoriteCount }}人收藏</text>
              <text class="status-tag favorited" v-if="dish.isFavorited">♥ 已收藏</text>
            </view>
          </view>
        </view>
        <view v-if="hotDishes.length === 0" class="no-data">
          <text>暂无热门菜品</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getBannerList, getHotDishes, bannerClick, getDishRecommend, recordClick, getUserDishStatus } from '@/api/diet'

export default {
  data() {
    return {
      bannerList: [
        {
          id: 1,
          title: "每日营养搭配指南",
          // 这里用项目绝对路径，适配任意页面位置
          image: "/static/images/banner/banner01.jpg"  
        },
         {
          id: 2,
          title: "每日营养搭配指南",
          // 这里用项目绝对路径，适配任意页面位置
          image: "/static/images/banner/banner02.jpg"  
        },
         {
          id: 3,
          title: "每日营养搭配指南",
          // 这里用项目绝对路径，适配任意页面位置
          image: "/static/images/banner/banner03.jpg"  
        },
         {
          id: 4,
          title: "每日营养搭配指南",
          // 这里用项目绝对路径，适配任意页面位置
          image: "/static/images/banner/banner04.jpg"  
        },
        {
          id: 5,
          title: "每日营养搭配指南",
          // 这里用项目绝对路径，适配任意页面位置
          image: "/static/images/banner/banner05.jpg"  
        }
      ],
      hotDishes: [],
      sortType: 'rating'
    }
  },
  onLoad() {
    this.loadHotDishes()
  },
  methods: {
    onImageError(e) {
      console.error('图片加载失败:', e.target.src);
    },
    // async loadBanners() {
    //   try {
    //     const res = await getBannerList({
    //       type: 'nutrition',
    //       status: 1,
    //       pageSize: 5
    //     })
    //     this.bannerList = res.rows || []
    //   } catch (error) {
    //     console.error('加载轮播图失败', error)
    //   }
    // },
    
    async loadHotDishes() {
      try {
        const res = await getHotDishes({
          sortType: this.sortType,
          pageSize: 10
        })
        console.log('API返回数据:', res)
        
        // 后端返回的是分页对象，直接包含菜品数组
        let dishList = []
        if (Array.isArray(res)) {
          // 直接返回数组
          dishList = res
        } else if (res && res.data && Array.isArray(res.data)) {
          // 返回包装对象
          dishList = res.data
        } else if (res && res.rows && Array.isArray(res.rows)) {
          // 分页对象的 rows 属性
          dishList = res.rows
        }
        
        console.log('解析后的菜品列表:', dishList)
        
        this.hotDishes = dishList.map(dish => {
          console.log('处理菜品数据:', dish)
          let fullImageUrl = '/static/images/default-dish.jpg'
          if (dish.imageUrl && typeof dish.imageUrl === 'string') {
            fullImageUrl = `http://localhost:8080${dish.imageUrl}`
          }
          console.log('图片URL:', fullImageUrl)
          
          return {
            id: dish.dishId,
            name: dish.dishName,
            image: fullImageUrl || '/static/images/default-dish.jpg',
            rating: dish.rating || 0,
            favoriteCount: dish.favoriteCount || 0,
            cuisine: dish.cuisine,
            taste: dish.taste,
            isFavorited: false // 默认未收藏，后续更新
          }
        })
        
        // 获取用户状态
        this.loadUserStatus()
        
        console.log('最终显示数据:', this.hotDishes)
      } catch (error) {
        console.error('加载热门菜品失败', error)
        this.hotDishes = []
      }
    },
    
    async viewBanner(banner) {
      // 统计点击
      try {
        await bannerClick(banner.id)
      } catch (error) {
        console.error('点击统计失败', error)
      }
      
      // 根据链接类型跳转
      if (banner.linkType === 'url') {
        uni.navigateTo({
          url: `/pages/common/webview/index?title=${banner.title}&url=${banner.linkUrl}`
        })
      } else if (banner.linkType === 'page') {
        uni.navigateTo({
          url: banner.linkUrl
        })
      } else if (banner.linkType === 'article') {
        uni.navigateTo({
          url: `/pages/article/detail/index?id=${banner.linkUrl}`
        })
      }
    },
    
    async gotoRecommend() {
      try {
        uni.showLoading({ title: '正在获取UPICF推荐...' })
        const userId = this.$store.getters.userId || uni.getStorageSync('userId') || 100
        const res = await getDishRecommend(userId)
        uni.hideLoading()
        
        if (res.recommendations && res.recommendations.length > 0) {
          // 将推荐结果存储到缓存
          uni.setStorageSync('upicf_recommendations', res.recommendations)
          uni.switchTab({
            url: '/pages/diet/recommend/index'
          })
        } else {
          uni.showToast({ title: '暂无推荐结果', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: 'UPICF推荐失败', icon: 'none' })
      }
    },
    
    gotoNutrition() {
      uni.navigateTo({
        url: '/pages/diet/nutrition/index'
      })
    },
    
    gotoSearch() {
      uni.navigateTo({
        url: '/pages/diet/search/index'
      })
    },
    
    gotoFavorites() {
      uni.navigateTo({
        url: '/pages/mine/favorites/index'
      })
    },
    
    changeSortType(type) {
      this.sortType = type
      this.loadHotDishes()
    },
    
    async viewDishDetail(dishId) {
      // 记录点击行为
      try {
        const userId = this.getUserId()
        await this.recordClick(dishId, userId)
      } catch (error) {
        console.error('记录点击失败:', error)
      }
      
      uni.navigateTo({
        url: `/pages/diet/detail/index?id=${dishId}`
      })
    },
    
    getUserId() {
      let userId = uni.getStorageSync('userId')
      if (!userId || userId === 'undefined' || isNaN(userId)) {
        userId = 100
        uni.setStorageSync('userId', userId)
      }
      return Number(userId)
    },
    
    async recordClick(dishId, userId) {
      try {
        const { recordClick } = await import('@/api/diet')
        await recordClick(dishId, userId)
        console.log('点击记录成功:', { dishId, userId })
      } catch (error) {
        console.error('点击记录失败:', error)
      }
    },
    
    async loadUserStatus() {
      try {
        const userId = this.getUserId()
        const dishIds = this.hotDishes.map(dish => dish.id)
        if (dishIds.length === 0) return
        
        const res = await getUserDishStatus(userId, dishIds)
        if (res.code === 200) {
          const { favorites } = res.data
          this.hotDishes.forEach(dish => {
            dish.isFavorited = favorites[dish.id] || false
          })
        }
      } catch (error) {
        console.error('获取用户状态失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.home-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// .banner-section {
//   margin-bottom: 30rpx;
// }

// .banner-swiper {
//   height: 300rpx;
// }

// .banner-image {
//   width: 100%;
//   height: 100%;
// }

// .banner-overlay {
//   position: absolute;
//   bottom: 0;
//   left: 0;
//   right: 0;
//   background: linear-gradient(transparent, rgba(0,0,0,0.6));
//   padding: 30rpx;
// }

// .banner-title {
//   color: white;
//   font-size: 28rpx;
//   font-weight: bold;
// }
.banner-section {
  width: 100%;
  height: 350rpx; /* 轮播图高度，根据需求调整 */
}
.banner-swiper {
  width: 100%;
  height: 100%;
}
.banner-image {
  width: 100%;
  height: 100%;
}
/* 标题覆盖层样式 */
.banner-overlay {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 20rpx;
  background: rgba(0, 0, 0, 0.5); /* 半透明黑底，让文字更清晰 */
}
.banner-title {
  color: #fff;
  font-size: 32rpx;
}

.quick-actions {
  background: white;
  padding: 40rpx 20rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: space-around;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.action-text {
  font-size: 24rpx;
  color: #333;
  margin-top: 10rpx;
}

.hot-dishes {
  background: white;
  padding: 30rpx 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.sort-options {
  display: flex;
}

.sort-item {
  font-size: 26rpx;
  color: #666;
  margin-left: 30rpx;
  
  &.active {
    color: #1890ff;
    font-weight: bold;
  }
}

.dish-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.dish-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
}

.dish-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.dish-meta {
  display: flex;
  align-items: center;
}

.rating-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
  margin-right: 20rpx;
}

.favorite-count {
  font-size: 24rpx;
  color: #999;
}

.status-tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-left: 10rpx;
  
  &.favorited {
    background: #ff4d4f;
    color: white;
  }
}

.dish-tags {
  display: flex;
  margin-bottom: 8rpx;
}

.tag {
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  margin-right: 8rpx;
  
  &.cuisine {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.taste {
    background: #f6ffed;
    color: #52c41a;
  }
}

.no-data {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
